<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery()">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-[10px]">
        <el-button type="success" icon="plus" @click="handleAdd()">新增</el-button>
        <el-button type="danger" :disabled="ids.length === 0" icon="delete" @click="handleDelete()">
          删除
        </el-button>
      </div>

      <el-table v-loading="loading" :data="tableData" border @selection-change="handleSelectRows">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" prop="id" />
        <el-table-column label="名称" prop="name" />
        <el-table-column label="创建人" prop="owner" />
        <el-table-column label="创建时间" prop="createdAt">
          <template #default="scope">
            {{ scope.row.createdAt ? formatDate(scope.row.createdAt) : "--" }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="updateAt">
          <template #default="scope">
            {{ scope.row.updateAt ? formatDate(scope.row.updateAt) : "--" }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-content">
        <el-pagination
          v-model:current-page="paging.page"
          v-model:page-size="paging.size"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <edit-form ref="editFormRef" @refresh="handleResetQuery" @openConfigForm="openConfigForm" />
    <config-form ref="configFormRef" @saveData="getConfigData" />
  </div>
</template>

<script setup>
import ConfigForm from "./configForm.vue"
import { formatDate } from "@/utils"
import ProfileAPI from "@/api/virtual-number/profile.api"
import EditForm from "./form.vue"
import useToggle from "@/hooks/useToggle"
const [loading, , setLoading] = useToggle()

const queryParams = ref({
  name: "",
})

const paging = ref({
  size: 10,
  page: 1,
  total: 0,
})

const ids = ref([])
const tableData = ref([])

const handleSizeChange = (e) => {
  paging.value.size = e
  getList()
}
const handleCurrentChange = (e) => {
  paging.value.page = e
  getList()
}

const handleQuery = () => {
  paging.value.page = 1
  getList()
}

const configFormRef = ref(null)
const openConfigForm = (e) => {
  configFormRef.value.init(e)
}
const getConfigData = (e) => {
  editFormRef.value.setConfig(e.index, e.data)
}

const getList = async () => {
  setLoading(true)
  const list = await ProfileAPI.getList({
    name: queryParams.value.name || void undefined,
    limit: paging.value.size,
    offset: (paging.value.page - 1) * paging.value.size,
  }).finally(() => setLoading(false))
  tableData.value = list

  const count = await ProfileAPI.getCount({
    name: queryParams.value.name || void undefined,
    limit: paging.value.size,
    offset: (paging.value.page - 1) * paging.value.size,
  }).finally(() => setLoading(false))
  paging.value.total = count
}

const queryFormRef = ref(null)
const handleResetQuery = () => {
  paging.value.page = 1
  paging.value.size = 10
  queryFormRef.value.resetFields()
  handleQuery()
}

const handleSelectRows = (e) => (ids.value = e.map((item) => item.id))

const editFormRef = ref(null)
const handleEdit = (row) => {
  editFormRef.value.init(row)
}
const handleAdd = () => editFormRef.value.init()

const handleDelete = (id) => {
  if (!id) {
    if (ids.value.length === 0)
      return ElMessage({
        message: "请选择要删除的数据",
        type: "warning",
      })

    return ElMessageBox.confirm(`是否确认删除已选中的${ids.value.length}条数据?`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      loading.value = true
      ProfileAPI.deleteByIds(ids.value).then(() => {
        loading.value = false
        ElMessage({
          message: "删除成功",
          type: "success",
        })
        getList()
      })
    })
  }
  ElMessageBox.confirm("是否确认删除该数据?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true
    ProfileAPI.deleteByIds([id]).then(() => {
      loading.value = false
      ElMessage({
        message: "删除成功",
        type: "success",
      })
      getList()
    })
  })
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.pagination-content {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
